using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using Microsoft.SharePoint;
using SharePoint.DataMapper;

namespace SharePoint.DataMapper
{
	[FieldMapper(typeof(SPFieldMultiChoice), SPFieldType.MultiChoice)]
	public class FieldMultiChoiceMapper : FieldMapper
	{
		protected override SPField AddFieldInternal(ListDataContext context, SPFieldCollection collection, Type propertyType, FieldAttribute attribute)
		{
			StringCollection choices = new StringCollection();
			foreach (string fieldName in Enum.GetNames(propertyType))
			{
				FieldInfo fieldInfo = propertyType.GetField(fieldName);
				choices.Add(Helpers.GetChoiceValue(fieldInfo));
			}
			string name = collection.Add(attribute.Field, attribute.FieldType, attribute.Required, false, choices);
			SPFieldMultiChoice field = (SPFieldMultiChoice)collection.GetFieldByInternalName(name);
			SetFieldPropertiesInternal(field, attribute);
			field.FillInChoice = false;//attribute.FillInChoice;
			return field;
		}

		protected override object SetFieldInternal(ListDataContext context, object value, Type propertyType)
		{
            if (value is SPFieldMultiChoiceValue)
            {
                return value;
            }
			string[] values = value.ToString().Split(',');
			SPFieldMultiChoiceValue choiceValues = new SPFieldMultiChoiceValue();
			foreach (string s in values)
			{
				FieldInfo fieldInfo = value.GetType().GetField(s.Trim());
				choiceValues.Add(Helpers.GetChoiceValue(fieldInfo));
			}
			return choiceValues;
		}

		protected override object GetFieldInternal(ListDataContext context, object value, Type propertyType)
		{
			SPFieldMultiChoiceValue choiceValues = (value is SPFieldMultiChoiceValue) ? (SPFieldMultiChoiceValue)value : new SPFieldMultiChoiceValue(value.ToString());
			if (typeof(SPFieldMultiChoiceValue) == propertyType)
            {
				return choiceValues;
            }
			if (typeof(Enum).IsAssignableFrom(propertyType))
			{
				Dictionary<string, string> values = Helpers.GetEnumValues(propertyType);
				string[] enumValues = new string[choiceValues.Count];
				for (int i = 0; i < choiceValues.Count; i++)
				{
					enumValues[i] = values[choiceValues[i]];
				}
				return Enum.Parse(propertyType, string.Join(",", enumValues));
			}
			return null;
		}
	}
}